/*
 * Copyright (c) 2017 Qunar.com. All Rights Reserved.
 */
package com.guoyu.project.common.ueditor.service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.guoyu.project.common.ueditor.UeditorDefaultConfig;
import com.guoyu.project.common.ueditor.model.ActionType;
import com.guoyu.project.common.ueditor.model.UeditorResult;

/**
 * @author: libo Date: 17-6-21 Time: 下午2:28
 * @version: \$Id$
 */
@Service
public class Base64UploadHandler extends AbstractHandler implements UeditorHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public UeditorResult handle(HttpServletRequest request, MultipartFile uploadFile) {
        byte[] data = Base64.decodeBase64(request.getParameter(UeditorDefaultConfig.FILE_FIELD_NAME));
        String fileName = "default.jpg";
        String extension = getExtension(fileName);
        String relativeFilePath = getRelativePath(fileName);
        File saveFile = new File(getPhysicalPathPre() + relativeFilePath);
        if (!saveFile.exists()) {
            try {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveFile));
                IOUtils.write(data, new BufferedOutputStream(new FileOutputStream(saveFile)));
                IOUtils.closeQuietly(bos);
            } catch (IOException e) {
                logger.error("Ueditor上传文件保存失败,fileName:{}", fileName, e);
                return UeditorResult.fail("上传的文件失败，失败原因:" + e.getMessage());
            }
        }
        UeditorResult ueditorResult = UeditorResult.success();
        ueditorResult.setOriginal(fileName);
        ueditorResult.setType(extension);
        ueditorResult.setUrl(getUrl(relativeFilePath));
        ueditorResult.setTitle(saveFile.getName());
        return ueditorResult;
    }

    @Override
    public ActionType getActionType() {
        return ActionType.upload64;
    }

}
